//
//  ChangeMobieVC.m
//  Cunli
//
//  Created by lilubin on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChangeMobieVC.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "Config.h"
#import "ChangeMobileVC2.h"
#import "JKCountDownButton.h"

@interface ChangeMobieVC ()

@property (nonatomic, assign) ChangeMobileType vctype;

@end

@implementation ChangeMobieVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"更换手机号";
    [self setAllUIKitAttributes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setAllUIKitAttributes
{
    //设置“获取验证码”背景图片
//    UIImage *getSecurityImage = [UIImage imageNamed:@"grayBtn03.png"];
//    getSecurityImage = [getSecurityImage stretchableImageWithLeftCapWidth:7 topCapHeight:0];
//    [_getCheckNumBtn setBackgroundImage:getSecurityImage forState:UIControlStateNormal];
    [_getCheckNumBtn addTarget:self action:@selector(getCheckNum:) forControlEvents:UIControlEventTouchUpInside];
//    [_getCheckNumBtn.titleLabel setTextColor:[UIColor colorWithHexString:@"0x2fa9f4"]];
    [_getCheckNumBtn setTitleColor:[UIColor colorWithHexString:@"0x2fa9f4"] forState:UIControlStateNormal];

    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
//    [rightBtn setBackgroundImage:[UIImage imageNamed:@"regnext"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(commitAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
    [_phoneBtn addTarget:self action:@selector(callAction) forControlEvents:UIControlEventTouchUpInside];
    [_phoneBtn setTitleColor:[UIColor colorWithHexString:@"0x2fa9f4"] forState:UIControlStateNormal];
    _phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_phoneBtn setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (void)commitAction:(UIButton *)button
{
    if (_mobileTextfield.text.length != 11 || _checkNumTextfield.text.length != 4) {
        [Config showHUDWithText:@"请检查电话号与验证码" andImage:@"error"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4];
    
    [params setObject:_mobileTextfield.text forKey:@"username"];
    [params setObject:@"bp" forKey:@"ctype"];
    [params setObject:_checkNumTextfield.text forKey:@"code"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    [MyDataService requestURL:@"checkcaptcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        
        NSLog(@"RegisterVC: Checkcode result:%@", result);
        
        //将username保存到本地，在后面的界面中还需要用到
        [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"username"] forKey:@"username"];
        
        NSString *response = [result objectForKey:@"response"];        
        
        if ([response isEqualToString:@"captcha"]) {
            ChangeMobileVC2 *nextVC = [[ChangeMobileVC2 alloc] init];
            [self.navigationController pushViewController:nextVC animated:YES];
        }
        else
        {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *errorStr = [errorDic objectForKey:@"text"];
            [Config showHUDWithText:errorStr andImage:@"error"];
            return;
        }
    } failureAction:^{
        [Config showHUDWithText:@"验证码错误" andImage:@"error"];
        return;
    }];

}

- (void)getCheckNum:(JKCountDownButton *)button
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:2]; //获取验证码需要的参数
    
    if (_mobileTextfield.text.length != 11 || ![_mobileTextfield.text isEqualToString:[Config getOwnUsername]]) {
        [Config showHUDWithText:@"请输入正确手机号码" andImage:@"error"];
        return;
    }
    else
    {
        button.enabled = NO;
        //button type要 设置成custom 否则会闪动
        [button startWithSecond:90];
        
        [button didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"%d秒",second];
            return title;
        }];
        [button didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            return @"重新获取";
        }];
    }
    
    //设置获取验证码需要的参数：username, rp, sign
    [params setObject:_mobileTextfield.text forKey:@"username"];
    [params setObject:@"bp" forKey:@"ctype"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //发送获取验证码的请求
    [MyDataService requestURL:@"captcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
//        NSLog(@"result:%@", result);
        NSString *response = result[@"response"];
        if ([response isEqualToString:@"error"])
        {
            NSDictionary *errorDic = result[@"error"];
            NSString *errorStr = errorDic[@"text"];
            [Config showHUDWithText:errorStr andImage:@"error"];
            [_getCheckNumBtn stop];
        }
        else
        {
        NSString *code = [result objectForKey:@"code"];
        NSLog(@"response:%@, code:%@", response, code);
        }
        
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }]; 
}


- (void)callAction
{
    NSString *telStr = @"tel:4000808135";
    UIWebView *callWebView = [[UIWebView alloc] init];
    [callWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telStr]]];
    [self.view addSubview:callWebView];
}



@end
